import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../res/appColor.dart';
import '../../model/FilterBarModel.dart';

class FilterBar extends StatefulWidget {
  @override
  _FilterBar createState() => _FilterBar();
}

class _FilterBar extends State<FilterBar> {
  int _filterIndex = -1;
  List<String> _title = ['区域', '价格', '房型', '面积'];
  List<Widget> _list = List();

  void _handleFilterIndexChanged(int index) {
    var filterBarData = Provider.of<FilterBarModel>(context);

    _filterIndex = filterBarData.index;
    if (_filterIndex == index) {
      _filterIndex = -1;
    } else {
      _filterIndex = index;
    }

    filterBarData.setIndex(_filterIndex);

    setState(() {});
  }

  @override
  void initState() {
    super.initState();

    _title.asMap().forEach((key, value) {
      _list.add(FilterBarButtonItem(
        title: value,
        filterIndex: key,
        onChanged: _handleFilterIndexChanged,
      ));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: AppColor.white,
      child: Row(
        children: _list,
      ),
    );
  }
}

class FilterBarButtonItem extends StatelessWidget {
  const FilterBarButtonItem({
    @required this.title,
    @required this.filterIndex,
    @required this.onChanged,
    Key key,
  }) : super(key: key);

  final String title;
  final int filterIndex;
  final ValueChanged<int> onChanged;

  void _handleTap() {
    onChanged(filterIndex);
  }

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: GestureDetector(
        child: Container(
          height: ScreenUtil().setWidth(90),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                this.title,
                style: TextStyle(
                  color: AppColor.textGray_6,
                  fontSize: ScreenUtil().setWidth(28),
                ),
              ),
              Icon(
                Icons.arrow_drop_down,
                color: AppColor.textGray_6,
              ),
            ],
          ),
        ),
        onTap: () {
          Scrollable.ensureVisible(context);
          _handleTap();
        },
      ),
    );
  }
}
